var express = require('express');
var router = express.Router();

const db = require("../utils/dbconfig")

// 获取用户类型信息
router.get('/users', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log(" req.query:", req.query)
  let params = []
  let sql = `select * from user where type="用户" `;
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    // console.log('result:', result)
    result.forEach(user => {
      if (user.birthday) {
        // 使用toISOString()获取ISO格式的日期字符串，然后截取前10个字符（年月日）
        user.birthday = user.birthday.toISOString().split('T')[0];
      }
    });
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("未搜索到")
  })
});
// 获取用户发布的帖子
router.get('/users/forum', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log(" req.query:", req.query)
  let params = []
  let sql = `select * from forum where userId='${req.query.id}' `;
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("未搜索到")
  })
});

// 获取商家类型信息
router.get('/merchants', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log(" req.query:", req.query)
  let params = []
  let sql = `select * from user where type="商家" `;
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    // console.log('result:', result)
    result.forEach(user => {
      if (user.birthday) {
        // 使用toISOString()获取ISO格式的日期字符串，然后截取前10个字符（年月日）
        user.birthday = user.birthday.toISOString().split('T')[0];
      }
    });
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("未搜索到")
  })
});
// 获取活动信息
router.get('/activities', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  // 预编译格式化函数
  const fastFormatter = (useUTC = true) => {
    const get = useUTC ?
      ['getUTCFullYear', 'getUTCMonth', 'getUTCDate', 'getUTCHours', 'getUTCMinutes', 'getUTCSeconds'] :
      ['getFullYear', 'getMonth', 'getDate', 'getHours', 'getMinutes', 'getSeconds'];
    return (date) => {
      const [y, m, d, h, min, s] = get.map(f => date[f]());
      return `${y}-${(m + 11).toString().slice(-2)}-${d.toString().padStart(2, '0')} ` +
        `${h.toString().padStart(2, '0')}:${min.toString().padStart(2, '0')}:` +
        `${s.toString().padStart(2, '0')}`;
    };
  };
  // 使用预编译函数
  const utcFormat = fastFormatter();
  console.log(" req.query:", req.query)
  let params = []
  let sql = `select * from activity `;
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    // console.log('result:', result)
    result.forEach(item => {
      if (item.activityStopTime) {
        item.activityStopTime = utcFormat(new Date(item.activityStopTime))
      }
    });
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("未搜索到")
  })
});

//插入报名活动信息
router.post('/activity_attend', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body)
  let params = {
    activityId: req.body[0],
    userId: req.body[1]
  }
  let sql = `insert into activity_attend set ?`;
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("插入失败")
  })
});
//退出活动
router.post('/activity_attend/delete', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body)
  let params = req.body
  let sql = `DELETE FROM activity_attend WHERE activityId=? and userId=? ;`;
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("插入失败")
  })
});

// 更新数据
router.post('/updata', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body)
  let list = req.body
  let sentence = ''
  let params = []
  for (let key in list) {
    if (list[key]) {
      sentence += `${key}=?,`
      params.push(list[key])
    }
  }
  sentence = sentence.slice(0, -1);//去掉末尾的逗号
  console.log("sentence:" + sentence)
  let sql = `update user set ${sentence} where userId =${req.body.userId} `;

  console.log("sql:" + sql)
  console.log("params:", params)

  db.sqlConnection(sql, params).then((res) => {
    console.log('res:', res)
  }).catch((err) => {
    res.status(400)
    console.log(err)
  })
  res.send('更新成功完成')

});
module.exports = router;

